package com.edu.strDemo;

import cn.hutool.core.date.DateTime;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author five-five
 * @version 1.0
 * todo：
 * @date 2021/7/12 21:04
 */
public class TestString01 {
    private static final String header = "'";
    private static final String foot = "'";


    public static void main(String[] args) {
        TestString01 testString01 = new TestString01();
        Map<String, String> map = testString01.parsingStr(MessageString.messageStr);
        System.out.println(map);
    }

    /**
     * 解析报文
     * 第一步：&}
     * 第二步：&,
     * 第三步："	"
     *
     * @param message 报文
     * @return 解析后的报文
     */
    public Map parsingStr(String message) {
        Map<String, String> map = new HashMap<>();
        for (String string : message.split("&}")) {
            //放入常量池
            string.intern();
            for (String str : string.split("&,")) {
                try {
                    // 去除花括号{
                    str = str.startsWith("{") ? str.substring(1) : str;
                    // 去除花括号}
                    str = str.endsWith("}") ? str.substring(0, str.length() - 1) : str;
                    //开始拿key，截取第一个|
                    String redisKey = str.substring(0, str.indexOf("|"));
                    //去除时间戳加入现在的时间
                    str = str.substring(str.indexOf("=") + 1);
                    //开始普遍的转换('='转换成':','|'转换成'#')
                    str = str.replace("=", ":").replace("|", "#");
                    //开始完善数据
                    //增加单引号
                    str = str.replace(":", foot + ":" + header);
                    str = str.replace(",", foot + "," + header);
                    StringBuilder stringBuilder = new StringBuilder(str);
                    //增加时间戳
                    stringBuilder.insert(0, header + "time" + foot + ":" + header + "" + new DateTime() + foot + "," + header);
                    //增加cold头
                    stringBuilder.insert(stringBuilder.indexOf("#") - 1, "," + header + "cold" + foot + ":" + header);
                    stringBuilder.append(foot);
                    //加入容器
                    map.put(redisKey,stringBuilder.toString().trim());
                } catch (Exception e) {
                    StringIndexOutOfBoundsException exception = new StringIndexOutOfBoundsException("当前报文有问题");
                    e.addSuppressed(exception);
                    exception.printStackTrace();
                }
            }
        }
        return map;
    }

}
